package com.leviassaf.androidbasics;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Activity;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.OnScanCompletedListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract.Directory;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

//104
public class ExternalData extends Activity implements OnItemSelectedListener, OnClickListener, OnScanCompletedListener, Runnable {
	
	private TextView txtvwMediaState, txtvwCanRead;
	private String strState;
	//105
	boolean booCanWrite, booCanRead;
	Spinner spinner;
	String[] arrStrPaths = {"Music", "Pictures", "Downloads"};
	//106
	File fileExternalStoragePublicDirectory = null;
	//107
	EditText edtSaveAs;
	Button btnConf, btnSave;
	//108
	File fileToBeSaved = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.externaldata);
		txtvwMediaState = (TextView)findViewById(R.id.txtvwMediaState);
		txtvwCanRead = (TextView)findViewById(R.id.txtvwCanRead);
		btnConf = (Button)findViewById(R.id.btnConfirm);
		btnSave = (Button)findViewById(R.id.btnSave);
		edtSaveAs = (EditText)findViewById(R.id.edtSaveAs);
		//105
		ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arrStrPaths);
		spinner = (Spinner)findViewById(R.id.spinner);
		spinner.setAdapter(arrayAdapter);
		//105
		spinner.setOnItemSelectedListener(this);
		
		//107
		btnConf.setOnClickListener(this);
		btnSave.setOnClickListener(this);
		
		checkState();

		this.setTitle(String.format("%s-%s", this.getTitle().toString(), this.getClass().getSimpleName()));
	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		// TODO Auto-generated method stub
		int intPosition = spinner.getSelectedItemPosition();
		switch (intPosition){
		case 0:
			fileExternalStoragePublicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
			break;
		case 1:
			fileExternalStoragePublicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
			break;
		case 2:
			fileExternalStoragePublicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
			break;
		}
		
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()){
		case R.id.btnSave:
			final String FILE_EXTENSION = "png";
			//108
			String strFileName = edtSaveAs.getText().toString();
			String strFileLast3Chars = strFileName.substring(strFileName.length());
			if (strFileLast3Chars != FILE_EXTENSION){
				strFileName = String.format("%s.%s", strFileName, FILE_EXTENSION);
			}
			fileToBeSaved = new File(fileExternalStoragePublicDirectory, strFileName);
			
			checkState();
			if (booCanWrite == booCanRead == true){
				
				//109
				fileExternalStoragePublicDirectory.mkdirs();
				
				try {
					InputStream inputStream = getResources().openRawResource(R.drawable.globe);
					OutputStream outputStream = new FileOutputStream(fileToBeSaved);
					byte[] arrBytData = new byte[inputStream.available()];
					inputStream.read(arrBytData);
					outputStream.write(arrBytData);
					inputStream.close();
					outputStream.close();
					
					//109
					Toast.makeText(this, "File has been saved", Toast.LENGTH_LONG).show();
					
					//110
					//MediaScanner has to scan the file 
					//to ensure the file is available for use
					MediaScannerConnection.scanFile(this, new String[]{fileToBeSaved.toString()}, null, this);
					
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			break;
		case R.id.btnConfirm:
			btnSave.setVisibility(View.VISIBLE);
			break;
		}
	}

	private void checkState(){
		
		strState = Environment.getExternalStorageState();
		if (strState.equals(Environment.MEDIA_MOUNTED)){
			txtvwMediaState.setText("Media can be written");
			booCanRead = booCanWrite = true;
		}else if (strState.equals(Environment.MEDIA_MOUNTED_READ_ONLY)){
			txtvwMediaState.setText("Media is read-only");
			booCanRead = true;
			booCanWrite = false;
		}
		else{
			txtvwMediaState.setText("Media cannot be written or read");
			booCanRead = false;
			booCanWrite = false;
		}
		
	}

	@Override
	public void onScanCompleted(String arg0, Uri arg1) {
		// TODO Auto-generated method stub
		runOnUiThread(this);
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		Toast.makeText(this, "Scan complete", Toast.LENGTH_SHORT).show();
	}
	
}
